<template>
  <div class="clue-view">
    <ContentField>
      <template v-slot:header> 查看线索 </template>
      <template v-slot:body>
        <el-divider content-position="left">条件选择</el-divider>
        <div>
          <div class="searchConditionArea" style="margin-top: 0px">
            <el-select
              v-model="condition.year"
              filterable
              placeholder="请选择年份"
            >
              <el-option
                v-for="year in years"
                :key="year.value"
                :label="year.label"
                :value="year.value"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="condition.pid"
              filterable
              placeholder="请选择省份"
              @change="getCitiesByPid"
              style="margin-left: 20px"
            >
              <el-option
                v-for="province in provinces"
                :key="province.id"
                :label="province.name"
                :value="province.id"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="condition.cid"
              filterable
              placeholder="请选择城市"
              @change="selectSchoolsByCid"
              style="margin-left: 20px"
            >
              <el-option
                v-for="city in cities"
                :key="city.id"
                :label="city.name"
                :value="city.id"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="condition.sid"
              filterable
              placeholder="请选择学校"
              style="margin-left: 20px"
            >
              <el-option
                v-for="shcool in schools"
                :key="shcool.id"
                :label="shcool.name"
                :value="shcool.id"
              >
              </el-option>
            </el-select>
          </div>
          <br />
          <div class="searchConditionArea" style="margin-top: 0px">
            <el-input
              placeholder="请输入姓名"
              v-model="condition.studentName"
              clearable
              style="width: 200px"
            >
            </el-input>
            <el-button
              type="primary"
              icon="el-icon-search"
              style="margin-left: 20px"
              @click="searchClueByCondition"
              >搜索</el-button
            >
          </div>
        </div>
        <el-divider></el-divider>
        <el-button
          type="success"
          plain
          @click="generateNotification"
          size="small"
        >
          生成通知书
        </el-button>
        <el-button
          type="warning"
          plain
          @click="deleteNotificationByIds"
          size="small"
        >
          删除通知书
        </el-button>
        <el-button plain size="small" @click="setClueReported">报道</el-button>
        <el-button type="info" plain size="small" @click="unsetClueReported">
          取消报道
        </el-button>
        <el-divider></el-divider>
        <div style="verflow-y: scroll; height: 400px">
          <el-table
            border
            ref="multipleTable"
            :data="curClues"
            tooltip-effect="dark"
            style="width: 100%"
            height="400"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="姓名">
                    <span>{{ props.row.studentName }}</span>
                  </el-form-item>
                  <el-divider content-position="left">详细信息</el-divider>
                  <el-form-item label="省份">
                    <span>{{ props.row.pname }}</span>
                  </el-form-item>
                  <el-form-item label="城市">
                    <span>{{ props.row.cname }}</span>
                  </el-form-item>
                  <el-form-item label="学校">
                    <span>{{ props.row.sname }}</span>
                  </el-form-item>
                  <el-form-item label="住址">
                    <span>{{ props.row.address }}</span>
                  </el-form-item>
                  <el-form-item label="身份证号">
                    <span>{{ props.row.idNum }}</span>
                  </el-form-item>
                  <el-form-item label="考号">
                    <span>{{ props.row.admissionTicket }}</span>
                  </el-form-item>
                  <el-form-item label="备注">
                    <span>{{ props.row.desc }}</span>
                  </el-form-item>
                  <el-divider content-position="left">联系方式</el-divider>
                  <el-form-item label="qq">
                    <span>{{ props.row.qq }}</span>
                  </el-form-item>
                  <el-form-item label="电话">
                    <span>{{ props.row.phoneNum }}</span>
                  </el-form-item>
                  <el-form-item label="邮箱">
                    <span>{{ props.row.email }}</span>
                  </el-form-item>
                  <el-form-item label="座机">
                    <span>{{ props.row.landline }}</span>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column label="录入日期" width="160">
              <template slot-scope="scope">{{ scope.row.entryTime }}</template>
            </el-table-column>
            <el-table-column prop="studentName" label="姓名" width="100">
            </el-table-column>
            <el-table-column prop="address" label="地址" show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              prop="notificationNumber"
              label="通知书编号"
              width="160"
            >
            </el-table-column>
            <el-table-column
              prop="notificationCreateTime"
              label="通知书创建时间"
              width="160"
            >
            </el-table-column>
            <el-table-column prop="reportedTime" label="报道时间" width="160">
            </el-table-column>
            <el-table-column prop="id" label="操作" width="120">
              <template slot-scope="{ row }">
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除？"
                  @confirm="handleDeleteConfirm(row.id)"
                >
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    circle
                    @click.stop="deleteClue"
                    slot="reference"
                  >
                  </el-button>
                </el-popconfirm>
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="updateClueBtnClick(row)"
                  style="margin-left: 10px"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="condition.curPageNum"
              :page-sizes="pageSizes"
              :page-size="condition.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="curCluesLength"
            >
            </el-pagination>
          </div>
        </div>
        <el-dialog
          title="线索信息"
          :visible.sync="updateClueInfoVisible"
          width="60%"
          center
        >
          <el-form ref="form" :model="curClue" label-width="80px">
            <el-alert
              title="必填项"
              type="error"
              :closable="false"
              style="width: 30%; margin-left: 80px"
            >
            </el-alert>
            <br />
            <el-form-item label="所在省市">
              <el-select
                v-model="curClue.pid"
                placeholder="请选择对应的省"
                @change="getCitiesByPid(1)"
              >
                <el-option
                  v-for="province in provinces"
                  :label="province.name"
                  :value="province.id"
                  :key="province.id"
                ></el-option>
              </el-select>
              <el-select
                v-model="curClue.cid"
                placeholder="请选择对应的城市"
                style="padding-left: 20px"
                @change="selectSchoolsByCid(1)"
              >
                <el-option
                  v-for="city in cities"
                  :label="city.name"
                  :value="city.id"
                  :key="city.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所在学校">
              <el-select v-model="curClue.sid" placeholder="请选择对应的学校">
                <el-option
                  v-for="school in schools"
                  :label="school.name"
                  :value="school.id"
                  :key="school.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="学生姓名" style="width: 30%">
              <el-input v-model="curClue.studentName"></el-input>
            </el-form-item>
            <el-form-item label="推荐人" style="width: 30%">
              <el-input v-model="curClue.uid" :disabled="true"></el-input>
            </el-form-item>
            <el-alert
              title="五选一"
              type="success"
              :closable="false"
              style="width: 30%; margin-left: 80px"
            >
            </el-alert>
            <br />
            <el-form-item label="QQ" style="width: 50%">
              <el-input v-model="curClue.qq"></el-input>
            </el-form-item>
            <el-form-item label="手机" style="width: 50%">
              <el-input v-model="curClue.phoneNum"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" style="width: 50%">
              <el-input v-model="curClue.email"></el-input>
            </el-form-item>
            <el-form-item label="座机" style="width: 50%">
              <el-input v-model="curClue.landline"></el-input>
            </el-form-item>
            <el-form-item label="准考证" style="width: 50%">
              <el-input v-model="curClue.admissionTicket"></el-input>
            </el-form-item>
            <el-alert
              title="选填项"
              type="warning"
              :closable="false"
              style="width: 30%; margin-left: 80px"
            >
            </el-alert>
            <br />
            <el-form-item label="身份证" style="width: 50%">
              <el-input v-model="curClue.idNum"></el-input>
            </el-form-item>
            <el-form-item label="家庭住址" style="width: 50%">
              <el-input v-model="curClue.address"></el-input>
            </el-form-item>
            <el-form-item label="备注" style="width: 80%">
              <el-input
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
                placeholder="请输入内容"
                v-model="curClue.remark"
              >
              </el-input>
            </el-form-item>

            <el-form-item>
              <el-button>取消</el-button>
              <el-button type="primary" @click="updateClueInfoConfirm">
                更新信息
              </el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </template>
    </ContentField>
  </div>
</template>

<script>
import axios from "axios";
import ContentField from "../../components/ContentField.vue";
export default {
  name: "ClueViewView",
  components: {
    ContentField,
  },
  created() {
    // 在创建完成后调用，获取所有省份
    this.getProvinces();
  },
  methods: {
    handleSizeChange(size) {
      this.condition.pageSize = size;
      this.searchClueByCondition();
    },
    handleCurrentChange(num) {
      this.condition.curPageNum = num;
      this.searchClueByCondition();
    },
    // 获取所有省份
    getProvinces() {
      let outer = this;
      this.$store.dispatch("getProvinces", {
        token: this.$store.state.user.jwt_token,
        success(resp) {
          outer.provinces = resp.data.data;
        },
        error(resp) {
          console.log(resp);
        },
      });
    },
    // 选择省份后调用，查询省份下的学校
    getCitiesByPid(flag) {
      let outer = this;
      this.condition.cid = "";
      this.condition.sid = "";
      if (flag == 1) {
        this.condition.pid = this.curClue.pid;
      }
      this.$store.dispatch("getCitiesByPid", {
        pid: this.condition.pid,
        token: this.$store.state.user.jwt_token,
        success(resp) {
          outer.cities = resp.data.data;
        },
        error(resp) {
          console.log(resp);
        },
      });
    },
    // 选择城市后调用，查询城市对应的学校
    selectSchoolsByCid(flag) {
      let outer = this;
      this.condition.sid = "";
      if (flag == 1) {
        this.condition.cid = this.curClue.cid;
      }
      this.$store.dispatch("selectSchoolsByCid", {
        cid: this.condition.cid,
        token: this.$store.state.user.jwt_token,
        success(resp) {
          outer.schools = resp.data.data;
        },
        error(resp) {
          console.log(resp);
        },
      });
    },
    // 多条件查询
    searchClueByCondition() {
      let outer = this;
      this.getClueByConditionNum();
      this.condition.offset =
        (this.condition.curPageNum - 1) * this.condition.pageSize;
      this.$store.dispatch("getClueByCondition", {
        condition: this.condition,
        token: this.$store.state.user.jwt_token,
        success(resp) {
          outer.curClues = resp.data.data;
        },
        error(resp) {
          console.log(resp);
        },
      });
    },
    // 获取线索数量
    getClueByConditionNum() {
      let outer = this;
      this.$store.dispatch("getClueByConditionNum", {
        condition: this.condition,
        token: this.$store.state.user.jwt_token,
        success(resp) {
          outer.curCluesLength = resp.data.data;
        },
        error(resp) {
          console.log(resp);
        },
      });
    },
    // 全选/全不选
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 多选框
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 图标点击函数，防止事件冒泡
    deleteClue() {},
    // 处理确认删除
    handleDeleteConfirm(id) {
      let outer = this;
      this.$store.dispatch("deleteById", {
        id: id,
        token: this.$store.state.user.jwt_token,
        success(resp) {
          console.log(resp);
          if (resp.data.code == 200) {
            outer.curClues = outer.curClues.filter((obj) => obj.id != id);
            outer.$message({
              type: "success",
              message: "成功删除!",
            });
          } else {
            outer.$message.error("删除失败：" + resp.data.message);
          }
        },
        error(resp) {
          console.log(resp);
        },
      });
    },
    // 点击修改按钮
    updateClueBtnClick(row) {
      // 展示对话框
      this.updateClueInfoVisible = true;
      // 将当前行的数据赋给对话框对应的当前线索
      this.curClue = JSON.parse(JSON.stringify(row));
      // 将当前的数据存下来，提交后，如果是非法操作，自动恢复
      this.oldClue = row;
      // 发送请求，加载当前select选项
      let outer = this;
      this.$store.dispatch("getCitiesByPid", {
        pid: this.curClue.pid,
        token: this.$store.state.user.jwt_token,
        success(resp) {
          outer.cities = resp.data.data;
        },
        error(resp) {
          console.log(resp);
        },
      });
      this.$store.dispatch("selectSchoolsByCid", {
        cid: this.curClue.cid,
        token: this.$store.state.user.jwt_token,
        success(resp) {
          outer.schools = resp.data.data;
        },
        error(resp) {
          console.log(resp);
        },
      });
    },
    // 点击对话框的更新按钮
    updateClueInfoConfirm() {
      let outer = this;
      this.$store.dispatch("updateClue", {
        clue: this.curClue,
        token: this.$store.state.user.jwt_token,
        success(resp) {
          if (resp.data.code == 200) {
            outer.updateClueInfoVisible = false;
            outer.$message({
              type: "success",
              message: "成功修改!",
            });
            // 为了保证数据的一致性，这里需要重新发一下请求
            outer.searchClueByCondition();
          } else {
            outer.$message.error("修改线索失败：" + resp.data.message);
            outer.curClue = outer.oldClue;
          }
        },
        error(resp) {
          console.log(resp);
        },
      });
    },
    // 生成通知书
    generateNotification() {
      let outer = this;
      let url = "/clue/notification/add";
      let config = {
        headers: {
          Authorization: "Bearer " + outer.$store.state.user.jwt_token,
        },
      };
      async function executeRequests() {
        for (let i = 0; i < outer.multipleSelection.length; i++) {
          let clue = outer.multipleSelection[i];
          try {
            const resp = await axios.post(
              url,
              {
                year: outer.condition.year,
                provId: clue.pid,
                clueId: clue.id,
              },
              config
            );
            if (resp.data.code == 200) {
              outer.$message({
                dangerouslyUseHTMLString: true,
                type: "success",
                message:
                  "姓名：" + clue.studentName + " <br/><br/>生成通知书成功!",
              });
            } else {
              outer.$message({
                dangerouslyUseHTMLString: true,
                type: "error",
                message:
                  "姓名：" +
                  clue.studentName +
                  " <br/><br/>生成通知书失败：" +
                  resp.data.message,
              });
            }
          } catch (error) {
            console.error(`请求 ${i + 1} 发生错误:`, error);
          }
          // 在最后一次请求完成之后执行
          if (i == outer.multipleSelection.length - 1) {
            outer.searchClueByCondition();
          }
        }
      }
      executeRequests();
      // for (let i = 0; i < this.multipleSelection.length; i++) {
      //   let clue = this.multipleSelection[i];
      //   while (flag != i) {}
      //   outer.$store.dispatch("generateNotification", {
      //     year: outer.condition.year,
      //     provId: clue.pid,
      //     clueId: clue.id,
      //     token: outer.$store.state.user.jwt_token,
      //     success(resp) {
      //       if (resp.data.code == 200) {
      //         outer.$message({
      //           dangerouslyUseHTMLString: true,
      //           type: "success",
      //           message:
      //             "姓名：" + clue.studentName + " <br/><br/>生成通知书成功!",
      //         });
      //       } else {
      //         outer.$message({
      //           dangerouslyUseHTMLString: true,
      //           type: "error",
      //           message:
      //             "姓名：" +
      //             clue.studentName +
      //             " <br/><br/>生成通知书失败：" +
      //             resp.data.message,
      //         });
      //       }
      //       // 在最后一次请求完成之后执行
      //       if (i == outer.multipleSelection.length - 1) {
      //         outer.searchClueByCondition();
      //       }
      //     },
      //     error(resp) {
      //       console.log(resp);
      //       // 在最后一次请求完成之后执行
      //       if (i == outer.multipleSelection.length - 1) {
      //         outer.searchClueByCondition();
      //       }
      //     },
      //   });
      // }
    },
    // 删除通知书
    deleteNotificationByIds() {
      let outer = this;
      for (let i = 0; i < this.multipleSelection.length; i++) {
        let temp = this.multipleSelection[i];
        this.$store.dispatch("deleteNotificationById", {
          id: temp.id,
          token: this.$store.state.user.jwt_token,
          success(resp) {
            if (resp.data.code == 200) {
              outer.$message({
                type: "success",
                message: "删除通知书成功",
              });
            } else {
              outer.$message({
                type: "error",
                message: "删除通知书失败：" + resp.data.message,
              });
            }
            // 在最后一次请求完成之后执行
            if (i == outer.multipleSelection.length - 1) {
              outer.searchClueByCondition();
            }
          },
          error(resp) {
            console.log(resp);
            // 在最后一次请求完成之后执行
            if (i == outer.multipleSelection.length - 1) {
              outer.searchClueByCondition();
            }
          },
        });
      }
    },
    // 设置报道
    setClueReported() {
      let outer = this;
      for (let i = 0; i < this.multipleSelection.length; i++) {
        let clue = this.multipleSelection[i];
        this.$store.dispatch("setClueReported", {
          id: clue.id,
          token: this.$store.state.user.jwt_token,
          success(resp) {
            if (resp.data.code == 200) {
              outer.$message({
                type: "success",
                message: clue.studentName + ": 设置报道成功",
              });
            } else {
              outer.$message({
                type: "error",
                message:
                  clue.studentName + ": 设置报道失败：" + resp.data.message,
              });
            }
            if (i == outer.multipleSelection.length - 1) {
              outer.searchClueByCondition();
            }
          },
          error(resp) {
            console.log(resp);
          },
        });
      }
    },
    // 取消报道
    unsetClueReported() {
      let outer = this;
      for (let i = 0; i < this.multipleSelection.length; i++) {
        let clue = this.multipleSelection[i];
        this.$store.dispatch("unsetClueReported", {
          id: clue.id,
          token: this.$store.state.user.jwt_token,
          success(resp) {
            if (resp.data.code == 200) {
              outer.$message({
                type: "success",
                message: clue.studentName + ": 取消报道成功",
              });
            } else {
              outer.$message({
                type: "error",
                message:
                  clue.studentName + ": 取消报道失败：" + resp.data.message,
              });
            }
            if (i == outer.multipleSelection.length - 1) {
              outer.searchClueByCondition();
            }
          },
          error(resp) {
            console.log(resp);
          },
        });
      }
    },
  },
  computed: {
    // 生成年份选项的，这里是从今年往前推50年
    years() {
      let years = [];
      for (let i = this.curYear - 50; i <= this.curYear; i++) {
        let obj = {};
        obj.label = i.toString();
        obj.value = i.toString();
        years.push(obj);
      }
      return years.reverse();
    },
  },
  data() {
    return {
      // 条件查询的条件
      condition: {
        year: "",
        pid: "",
        cid: "",
        sid: "",
        studentName: "",
        pageSize: 8,
        curPageNum: 1,
        offset: 0,
      },
      oldClue: {},
      // 获取当前年份
      curYear: new Date().getFullYear(),
      provinces: [],
      cities: [],
      schools: [],
      // 查询出来的线索
      curClues: [],
      // 线索条数
      curCluesLength: 0,
      // 多项（选中的）列表
      multipleSelection: [],
      // 更新对话框显示标识
      updateClueInfoVisible: false,
      curClue: {},
      // 分页参数
      pageSizes: [3, 5, 8, 10, 15, 20],
    };
  },
};
</script>

<style scoped>
.searchConditionArea {
  display: flex;
  justify-content: center; /* 在水平方向上居中 */
  align-items: center; /* 在垂直方向上居中 */
  margin-top: 20px;
}

.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.el-divider--horizontal {
  display: block;
  height: 1px;
  width: 100%;
  margin: 15px 0;
}

.pagination-container {
  display: flex;
  justify-content: center; /* 使用 flex 布局将内容水平居中 */
  align-items: center; /* 使用 flex 布局将内容垂直居中 */
}
</style>
